package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnShowListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.isunland.managesystem.R;
import com.isunland.managesystem.common.ImageTools;
import com.isunland.managesystem.utils.FileUtil;
import java.io.File;

/**
 * 附件选择Dialog
 *
 * @author wangyanan
 */
public class ExtraUpLoadDialogFragment extends DialogFragment {
  public static final int REQUEST_CODE = 10;
  public static final int TYPE_ALL = 0;
  public static final int TYPE_PHOTO = 1;
  public static final String EXTRA_RESULT = "com.isunland.managesystem.ui.EXTRA_RESULT";
  public static final String EXTRA_ABSOLUTEPATH = "com.isunland.managesystem.ui.EXTRA_ABSOLUTEPATH";
  //没有压缩的路径
  public static final String EXTRA_POSITION = "com.isunland.managesystem.ui.EXTRA_POSITION";
  //拍照,图库,文件管理
  public static final String VALUE_CLEAR = "com.isunland.managesystem.ui.VALUE_CLEAR";
  @SuppressWarnings("unused") public static final String VALUE_FILE =
      "com.isunland.managesystem.ui.VALUE_FILE";
  protected static final int CAMERA = 0;
  protected static final int ALBUM = 1;
  protected static final int FILE_EXPLORER = 2;
  private static final int REQUEST_CAMERA = 0;
  private static final int REQUEST_ALBUM = 1;
  private static final int REQUEST_EXPLORER = 2;
  private static final String EXTRA_FILE = "com.isunland.managesystem.ui.EXTRA_FILE";
  private static final String EXTRA_TYPE = "com.isunland.managesystem.ui.EXTRA_TYPE";
  private File mFile;
  private AlertDialog mDialog;
  private String mFilePath = "";
  private int mType;// 类型0代表所有，1代表只有图库和相册。
  private int filePosition;

  public static ExtraUpLoadDialogFragment newInstance(String filePath) {
    return newInstance(filePath, TYPE_ALL);
  }

  public static ExtraUpLoadDialogFragment newInstance(String filePath, int type) {
    Bundle argsBundle = new Bundle();

    argsBundle.putString(EXTRA_FILE, filePath);
    argsBundle.putInt(EXTRA_TYPE, type);
    ExtraUpLoadDialogFragment fragment = new ExtraUpLoadDialogFragment();
    fragment.setArguments(argsBundle);
    return fragment;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    mFilePath = getArguments().getString(EXTRA_FILE);
    mType = getArguments().getInt(EXTRA_TYPE);
    super.onCreate(savedInstanceState);
  }

  @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) {

    if (TextUtils.isEmpty(mFilePath)) {
      mDialog = chooseFileDialog();
    } else {
      mDialog = reChooseDialog();
    }

    return mDialog;
  }

  private AlertDialog reChooseDialog() {

    final AlertDialog dialogReChoose =
        new AlertDialog.Builder(getActivity()).setMessage(R.string.attachmentConfirm)
            .setPositiveButton(R.string.watch, null)
            .setNeutralButton(R.string.clearChoose, null)
            .create();
    dialogReChoose.setOnShowListener(new OnShowListener() {

      @Override public void onShow(final DialogInterface dialog) {
        Button positiveButton = dialogReChoose.getButton(AlertDialog.BUTTON_POSITIVE);
        Button neutralButton = dialogReChoose.getButton(AlertDialog.BUTTON_NEUTRAL);

        positiveButton.setOnClickListener(new OnClickListener() {

          @Override public void onClick(View v) {
            if (!TextUtils.isEmpty(mFilePath)) {
              FileUtil.openFile(new File(mFilePath), getActivity());
              dialogReChoose.dismiss();
            }
          }
        });
        neutralButton.setOnClickListener(new OnClickListener() {

          @Override public void onClick(View v) {
            setResult(VALUE_CLEAR, "");
            dialog.dismiss();
          }
        });
      }
    });

    return dialogReChoose;
  }

  public AlertDialog chooseFileDialog() {

    String[] extraFileStrs = getActivity().getResources().getStringArray(R.array.extraFile);
    String[] extraPicStrs = getActivity().getResources().getStringArray(R.array.extraPicture);
    String[] extra;
    if (mType == TYPE_PHOTO) {
      extra = extraPicStrs;
    } else {
      extra = extraFileStrs;
    }
    final AlertDialog dialogChoose = new AlertDialog.Builder(getActivity()).setItems(extra, null)

        .create();
    dialogChoose.setOnShowListener(new OnShowListener() {

      @Override public void onShow(DialogInterface dialog) {
        ListView lv = dialogChoose.getListView();
        lv.setOnItemClickListener(new OnItemClickListener() {

          @Override
          public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            filePosition = position;
            switch (position) {
              case CAMERA:
                //							if (Build.VERSION.SDK_INT > 23) {
                //								int checkCamera = ContextCompat.checkSelfPermission(getActivity(),
                //										Manifest.permission.CAMERA);
                //								if (checkCamera != PackageManager.PERMISSION_GRANTED) {
                //									ActivityCompat.requestPermissions(getActivity(),
                //											new String[] { Manifest.permission.CAMERA }, CAMERA);
                //								}
                //								takePhoto();
                //							}else{
                takePhoto();
                //							}
                break;
              case ALBUM:
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                startActivityForResult(intent, REQUEST_ALBUM);
                break;
              case FILE_EXPLORER:
                Intent intent2 = new Intent(Intent.ACTION_GET_CONTENT);
                intent2.setType("*/*");
                intent2.addCategory(Intent.CATEGORY_OPENABLE);

                startActivityForResult(
                    Intent.createChooser(intent2, getString(R.string.chooseFileExplorer)),
                    REQUEST_EXPLORER);
                break;

              default:
                break;
            }
          }
        });
      }
    });
    return dialogChoose;
  }

  private void takePhoto() {
    if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {

      mFile = new File(FileUtil.getFileDir(), System.currentTimeMillis() + ".jpg");
      //noinspection ResultOfMethodCallIgnored
      mFile.getParentFile().mkdirs();

      Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
      intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mFile));
      startActivityForResult(intent2, REQUEST_CAMERA);
    } else {
      Toast.makeText(getActivity(), R.string.check_sd_card, Toast.LENGTH_SHORT).show();
    }
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) {
      return;
    }
    String absolutePath = "";
    switch (requestCode) {

      case REQUEST_CAMERA:
        absolutePath = mFile.getAbsolutePath();
        mFile = compress(mFile.getAbsolutePath());

        break;
      case REQUEST_ALBUM:

        Uri uri = data.getData();
        String path = FileUtil.getPath(getActivity(), uri);
        absolutePath = path;
        mFile = compress(path);
        break;
      case REQUEST_EXPLORER:

        Uri uri1 = data.getData();
        String path1 = FileUtil.getPath(getActivity(), uri1);
        absolutePath = path1;
        if (path1 == null) return;
        mFile = new File(path1);
        break;
      default:
        break;
    }
    if (null == mFile) {
      Toast.makeText(getActivity(), R.string.fileNotFound, Toast.LENGTH_SHORT).show();
      mDialog.dismiss();
      return;
    }
    setResult(mFile.getAbsolutePath(), absolutePath);
    mDialog.dismiss();
    super.onActivityResult(requestCode, resultCode, data);
  }

  /**
   * 压缩图片
   */
  private File compress(String path) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = false;
    options.inPreferredConfig = Bitmap.Config.RGB_565;
    options.inDither = true;
    Bitmap bitmap = BitmapFactory.decodeFile(path, options);
    if (bitmap == null) {
      return null;
    }
    Bitmap newBitmap = ImageTools.zoomBitmap(bitmap, 400, 400);
    bitmap.recycle();
    return ImageTools.savePhotoToSDCard(newBitmap, FileUtil.getFileDir(),
        System.currentTimeMillis() + "");
  }

  private void setResult(String result, String absolutePath) {
    if (getTargetFragment() == null) return;
    Intent i = new Intent();
    i.putExtra(EXTRA_RESULT, result);
    i.putExtra(EXTRA_ABSOLUTEPATH, absolutePath);
    i.putExtra(EXTRA_POSITION, filePosition);

    getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, i);
  }
}
